<?php

namespace app\api\controller;

use app\common\model\User;
use app\common\model\WechatFans;
use app\common\service\TokenService;
use app\common\service\UserService;
use app\common\service\WxService;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use service\WechatService;
use think\Exception;
use think\exception\PDOException;
use think\facade\Cache;
use think\facade\Log;
use WeChat\Oauth;

class AuthController extends BaseApiController
{
    protected $is_auth = false;

    /**
     * @return void
     * @throws InvalidConfigException
     * @throws Exception
     * @throws PDOException
     */
    public function wxMiniLogin()
    {
        $code = input('code');
        $config = [
            'appid' => sysconf("wx_shop_mini_appid"),
            'appsecret' => sysconf("wx_shop_mini_appsecret"),
        ];
        $mini = new Crypt($config);
        $res = $mini->session($code);
        $user = (new User())->where("openid", $res['openid'])->find();
        if (!$user) {
            $openid = $res['openid'];
            $fans = (new WechatFans())->where("appid", $config["appid"])
                ->where("openid", $openid)
                ->find();
            $user = User::create([
                'name' => Data::randomCode(5, 3),
                'avatar'=>'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
                "openid" => $openid,
                "session_key" => $res["session_key"]
            ]);
            if (!$fans) {
                WechatFans::create([
                    "appid" => $config["appid"],
                    "openid" => $openid,
                    "user_id" => $user["id"]
                ]);
            }
        } else {
            User::update([
                "session_key" => $res["session_key"]
            ], ['id' => $user["id"]]);
        }
        $token = TokenService::generateJwt($user["id"]);
        $this->successReturn(['token' => $token], '登录成功');
    }

    public function getOfficialAccountLoginUrl()
    {
        $redirect_url = input('redirect_url');
        $state = input('state');
        $url = (new WxService())->wxOauth($redirect_url, $state);
        $this->successReturn(['url' => $url]);
    }

    public function officialAccountLogin()
    {
        $code = input('code');
        $_GET['code'] = $code;
        $info = (new WxService())->getWxInfo();
        if (!$info) {
            $this->errorReturn(null, '登录失败');
        }

        $res = UserService::updateFansInfo($info, UserService::TYPE_OFFICIAL_ACCOUNT, sysconf('wemini_appid'));
        $fans = $res["fans"];
        $data = $this->wechatLogin($fans);
        $this->successReturn([
            'token' => $data['token'],
        ], $data['msg']);
    }

    protected function wechatLogin($fans)
    {
        $user_model = new User();
        $fans_model = new WechatFans();
        if (env("is_debug")) {
            $user = $user_model->get(['id' => "56"]);
            return [
                'token' => TokenService::generateJwt(56),
                'msg' => '登录成功',
                'user' => $user
            ];
        } else {
            if (!empty($fans['user_id']) && ($user = $user_model->get(['id' => $fans['user_id']]))) {
                $token = TokenService::generateJwt($user['id']);
                UserService::updateUserByFans($user, $fans);
                return [
                    'token' => $token,
                    'msg' => '登录成功',
                    'user' => $user
                ];
            } else {
                if (isset($fans['unionid']) && !empty($fans['unionid'])) {
                    $fans_list = $fans_model->where('unionid', $fans['unionid'])->select();
                    foreach ($fans_list as $item) {
                        if (!empty($item['user_id']) && ($user = $user_model->get(['id' => $item['user_id']]))) {
                            WechatFans::update(['user_id' => $item['user_id']], ['id' => $fans['id']]);
                            $token = TokenService::generateJwt($user['id']);
                            UserService::updateUserByFans($user, $fans);
                            return [
                                'token' => $token,
                                'msg' => '登录成功',
                                'user' => $user
                            ];
                        }
                    }
                }

                $fans_key = rand_str(32);
                Cache::set("fans" . $fans_key, $fans['id']);
                $this->successReturn(['need_bind_phone' => 1, 'fans_key' => $fans_key], '未绑定手机');
            }
        }


    }

}